import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import dictionary.RadiusDict;


public class TestParser {

	public RadiusPacket parse(String fileName) throws IOException {
		RadiusDict radDict = RadiusDict.getInstance(Config.getInstance().getRadiusDictionaryPath());
		Path file = Paths.get(fileName);
		BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8);
		
		//create radius packet POJO with all AVPs from request
		RadiusPacket radPacket = new RadiusPacket();
		
		String line = null;

		//parse the lines in the test file and extract command code and avp name-value pairs
		while ((line = reader.readLine()) != null) {
			if (line.endsWith(":=")) {  //then this is radius command code line
				String command = line.substring(0, line.length() - 2); //get the command string without the delimiter at the end of the line
				radPacket.setCommandCode(radDict.getCommandCode(command));
			}
			if (line.startsWith("-")) { //then this is avp line and we need to split it in a name-value format
				String tmp = line.substring(2); // but first get rid of "- " prefix
				RadiusAttribute radAttr = createRadAttr(tmp.split(":="));
				radPacket.addRadiusAttribute(radAttr);
			}
		}
		//TODO: create radius packet identifier
		//TODO: create radius packet authenticator
		
		return radPacket;
	}
	
	private RadiusAttribute createRadAttr(String[] tmp) {
		String attrName = tmp[0];
		String attrValue = tmp[1];
		/*
		 * In future use factory pattern (or dependency injection(GUICE) maybe) to create RadiusAttribute 
		 */
		RadiusAttribute attr  = new RadiusAttribute(attrName, attrValue);
		//System.out.println("attrname = " + attrName);
		//System.out.println("attrvalue = " + attrValue);
		
		return attr;
	}
}
